const fs = require('fs')

import { ObjectId, MongoClient } from 'mongodb'
import YAML from 'yamljs'
//var mongoose = require('mongoose');

import BaseResult from '../lib/BaseResult'

const { mongo } = YAML.parse(fs.readFileSync('./server/config.yaml').toString());
const url = mongo.host;
// mongoose.connect('mongodb://localhost/test');

class PerformanceController {
    static async report(ctx) {
        let data = ctx.request.body;
        let timing = data.timing;
        let performance = data.performance;
        return new Promise((resolve) => {
            MongoClient.connect(url, function(err, db) {
                if (err) throw err;
                console.log('数据库已创建');
                var dbo = db.db("rmos");
                let dbCount = 1;
                function close(){
                    dbCount--;                    
                    if(dbCount==0){
                        console.log('关闭连接')
                        db.close();
                    }
                };
               for(let p in performance){
                dbCount++;
                  let item = performance[p];
                //   console.log(p)
                 // let item = performance[p];
                  let where  = {url:item.url};
                   dbo.collection('performance')
                   .find(where)
                   .toArray(function(err, res) {
                       if(res.length>0){
                        // console.log(item.duration)
                        // console.log(res[0].duration) 
                        // console.log((item.duration+res[0].duration)/2)
                        item.duration=(item.duration+res[0].duration)/2;
                        item.minDuration = Math.min(item.duration,res[0].minDuration);
                        item.maxDuration = Math.max(item.duration,res[0].maxDuration);
                        // console.log(item)
                        dbo.collection('performance')
                        .updateOne(where,{
                            $set:item
                        },function(){
                            close()
                        })
                       }else{
                        item.minDuration = item.duration;
                        item.maxDuration = item.duration;
                          dbo.collection("performance")
                          .insertOne(item,function(){
                            close()
                        })
                       }
                   })
               }

                // dbo.collection("performance").insertOne(performance, function(err, res) {
                //     if (err) throw err;
                //     // console.log("文档插入成功");
                //     //ctx.body = "文档插入成功";
                //   //  ctx.body = new BaseResult(0, 0, null);
                //   db.close();
                // });
                dbo.collection("timing").insertOne(timing, function(err, res) {
                   
                    if (err) throw err;
                    // console.log("文档插入成功");
                    //ctx.body = "文档插入成功";
                // ctx.body = new BaseResult(0, 0, null);
                   
                    close();
                });
                
                ctx.body = new BaseResult(0, 0, null);
                resolve();
            });
        })
    }
    static async reportSimple(ctx) {
        let data = ctx.request.body;
        return new Promise((resolve) => {
            MongoClient.connect(url, function(err, db) {
                if (err) throw err;
                console.log('数据库已创建');
                var dbo = db.db("rmos");
                // var myobj = { name: "菜鸟教程", url: "www.runoob" };
                dbo.collection("performance").insertOne(data, function(err, res) {
                    if (err) throw err;
                    // console.log("文档插入成功");
                    //ctx.body = "文档插入成功";
                    ctx.body = new BaseResult(0, 0, null);
                    resolve();
                    db.close();
                });
            });
        })
    }
    static async list(ctx) {
        let query = ctx.query;
        //    let db = new DB('performance');
        //    let data = await db.query().end();
        //    ctx.body = new BaseResult(0,0,data);
        return new Promise((resolve) => {
            MongoClient.connect(url, function(err, db) {
                if (err) throw err;
                var dbo = db.db("rmos");
                console.log('query.appKey')
                console.log(query.appKey)
                dbo.collection("performance").find().toArray(function(err, result) { // 返回集合中所有数据
                    if (err) throw err;
                    // console.log(result);
                    ctx.body = new BaseResult(0, 0, result);
                    resolve()
                    db.close();
                });
            });
        })
    }
}
export default  PerformanceController;